package com.jin.crud.common.config.security;

import com.jin.crud.bean.LoginUser;
import com.jin.crud.common.constants.Constants;
import com.jin.crud.common.utils.ServletUtils;
import com.jin.crud.common.utils.StringUtils;
import com.jin.crud.common.utils.ip.AddressUtils;
import com.jin.crud.common.utils.ip.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author yuxuejin
 * @Date 2021/11/25 22:00
 * @Description: token验证处理
 */
@Component
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        //String token = IdUtils.fastUUID();
        //loginUser.setToken(token);
        //System.out.println(loginUser);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        //private Set<String> permissions;

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", loginUser.getUserId());
        claims.put("username", loginUser.getUsername());
        claims.put("loginTime", loginUser.getLoginTime());
        //claims.put("expireTime", loginUser.getExpireTime());
        //claims.put("ipaddr", loginUser.getIpaddr());
        //claims.put("loginLocation", loginUser.getLoginLocation());
        //claims.put("browser", loginUser.getBrowser());
        //claims.put("os", loginUser.getOs());
        //claims.put("permissions", loginUser.getPermissions());

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();


        //Map<String, Object> claims = new HashMap<>();
        //claims.put(Constants.LOGIN_USER_KEY, token);
        //return createToken(claims);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    private void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = Long.parseLong(loginUser.getExpireTime());
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(String.valueOf(System.currentTimeMillis()));
        Long endTime = Long.parseLong(loginUser.getLoginTime()) + (expireTime * MILLIS_MINUTE);
        loginUser.setExpireTime(String.valueOf(endTime));
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);

            // 解析对应的权限以及用户信息
            //String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            //String userKey = getTokenKey(uuid);
            //LoginUser user = redisCache.getCacheObject(userKey);
            //claims.getSubject();
            return new LoginUser(String.valueOf(claims.get("userId")));
        }
        return null;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
